package com.btcode.db.result;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class DataHelper {

    /**
     * 行转列
     *
     * @param combiteField 依据哪个字段合并行
     * @param rowToColFields 哪些字段要行转列
     * @param colTextField 哪一列要由行放到列，比如污染物
     */
    public static List<Row> RowToCol(List<Row> data, String combiteField,
        List<String> rowToColFields, String colTextField) {
        List<Row> result = new LinkedList<>();

        String curCombiteValue = null;
        Row curRow = new Row();
        for (Row row : data) {
            String colText = row.getSafeString(colTextField);
            String combiteValue = row.getSafeString(combiteField);
            if (!combiteValue.equals(curCombiteValue)) {
                curRow = new Row();
                if (curRow != null) {
                    result.add(curRow);
                }
            }

            Set<String> columns = row.keySet();

            for (String column : columns) {
                if (rowToColFields.contains(column)) {
                    curRow.put(column + "_" + colText, row.get(column));
                }
                else {
                    curRow.put(column, row.get(column));
                }
            }

            curCombiteValue = combiteValue;
        }
        return result;
    }

}
